package com.example.mobile2021606163crw0523;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private RecyclerView rvMainNews;
    String url = "http://10.110.147.117:3000/news";
    //2.定义Okgttp客户端网络访问对象
    OkHttpClient okHttpClient = new OkHttpClient();
    Gson gson = new Gson();
    Type type = new TypeToken<List<News>>(){}.getType();
    List<News> newsList = new ArrayList<>();
    NewsRVAdapter newsRVAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //声明适配器，用线性布局
        rvMainNews.setLayoutManager(new LinearLayoutManager(this));
        //1.定义访问路径字符串和使用子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //3.在子线程的run（）方法中，定义网络访问请求
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                //4.根据网络请求request，由OkhttpClient客户端创建请求执行对象call
                Call call = okHttpClient.newCall(request);
                //5.采用异步方式执行，将call加入到执行队列中去，待有空隙时执行
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String result = response.body().string();
                        newsList = gson.fromJson(result, type);
                        Log.i("TAG", "onResponse"+newsList.size());
                        //Log.i("TAG", "onResponse"+result);
                        //在网络访问成功返回方法中，创建适配器对象
                        newsRVAdapter = new NewsRVAdapter(newsList);
                        //调用runOnUiThread方法，将适配器赋给列表控件
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rvMainNews.setAdapter(newsRVAdapter);
                            }
                        });
                    }
                });
            }
        }).start();
    }

    private void initView() {
        rvMainNews = (RecyclerView) findViewById(R.id.rvMainNews);
    }
}